<template>
    <div class="goods_sku">
        <van-nav-bar title="规格" left-arrow fixed @click-left="onClickLeft" />
        <div class="goods_btn">
            <van-button style="margin-right: .2rem;" type="danger" size="mini" icon="plus"
                @click="addSku">新增</van-button>
            <van-button type="info" size="mini" icon="edit">编辑</van-button>
        </div>
        <van-field v-model="goodsName" label="商品模型" placeholder="请选择" @click="showGood = true" readonly is-link
            input-align="right" />
        <van-field :border="false" name="checkboxGroup" v-for="item, index in spec" :label="item.name" :key="index">
            <template #input>
                <van-checkbox-group v-model="item.select_ids" direction="horizontal" @change="skuChange">
                    <van-checkbox v-for="item2, index2 in item.spec_items" :key="index2" :name="item2.id" shape="square"
                        checked-color="#ee0a24">{{ item2.item }}</van-checkbox>
                </van-checkbox-group>
            </template>
        </van-field>
        <div v-if="setsSkuList.length>0" v-for="item3,index3 in setsSkuList" class="sku_list">
            <div class="sku_item" @click="openEditSku(index3)">
                <img :src="item3.img" alt="">
                <div class="sku_name"> {{ item3.name && item3.colorname ? `${item3.name}/${item3.colorname}` : item3.name ||
                    item3.colorname }}</div>
                <div class="sku_price">
                    <div>￥{{ item3.price || 0 }}</div>
                    <div>库存:{{ item3.stock || 0 }}</div>
                </div>
                <van-icon class="sku_icon" name="arrow" />
            </div>
        </div>

        <van-button round block type="info" @click="onSubmit" style="width: 95%;margin: 0.32rem auto;"
            color="linear-gradient(to right, #FF5851, #E9011B)">提交</van-button>
        <van-popup v-model="showGood" position="bottom">
            <van-cascader :field-names="fieldNames" v-model="cascaderValue" title="请选择" :options="options"
                @close="showGood = false" @finish="onFinish" />
        </van-popup>
        <van-popup v-model="editSkuShow" :style="{ width: '70%' }" round>
            <div class="popup_title">价格库存</div>
            <div class="good-box">
                <van-uploader v-model="goodImg" :max-count="1" :after-read="afterGoodReadFront"
                    :before-delete="uploadGoodDleteFront" />
            </div>
            <div class="field_input">
                <van-field required label-width="1.2rem" v-model="price" label="价格" placeholder="请输入价格"
                    input-align="right" />
                <van-field required label-width="1.2rem" v-model="stock" label="库存" placeholder="请输入库存" clearable
                    input-align="right" />
            </div>
            <div class="popup_btn_list">
                <van-button class="popup_btn" size="small" round @click="editSkuShow = false">取消</van-button>
                <van-button class="popup_btn" type="primary" size="small"
                    color="linear-gradient(to right, #FF5851, #E9011B)" round @click="updateSku">确定</van-button>
            </div>
        </van-popup>
    </div>
</template>
<script>
import { getOssParams, uploadImage, uploadDelete } from "@/api/upload";

export default {
    name: 'sku',
    data() {
        return {
            goodsName: "",
            showGood: false,
            fieldNames: {
                text: "name",
                value: "id",
                children: "children",
            },
            cascaderValueMcc: '',
            options: [
                {
                    id: 1,
                    name: '手机',
                }
            ],
            cascaderValue: '',
            selectList: [],
            spec: [
                {
                    name: "内存",
                    id: 421,
                    select_ids: [],
                    spec_items: [
                        {
                            id: 1,
                            item: "64G"
                        },
                        {
                            id: 2,
                            item: "128G"
                        },
                        {
                            id: 3,
                            item: "256G"
                        }
                    ]
                },
                {
                    name: "颜色",
                    id: 422,
                    select_ids: [],
                    spec_items: [
                        {
                            id: 4,
                            item: "黑色"
                        },
                        {
                            id: 5,
                            item: "白色"
                        },
                        {
                            id: 6,
                            item: "红色"
                        }
                    ]
                }
            ],
            setsSkuList: [],
            selectedCombinations: [],
            editSkuShow: false,
            goodImg: [],
            price: "",
            stock: "",
            selectedSkuIndex: ''
        }
    },
    created() {

    },
    methods: {
        onClickLeft() {
            this.$router.back()
        },
        //商品模型
        onFinish({ selectedOptions }) {
            this.showGood = false;

            this.selectList = selectedOptions;

            selectedOptions = selectedOptions.filter((item) => {
                return item.value !== 0;
            });

            //   console.log(selectedOptions, "333");

            this.goodsName = selectedOptions.map((option) => option.name).join("/");
        },
        skuChange(val) {
            const memorySelections = this.spec[0].select_ids; // 内存选择
            const colorSelections = this.spec[1].select_ids; // 颜色选择

            this.selectedCombinations = []; // 清空之前的组合

            // 生成所有可能的组合
            if (memorySelections.length > 0 && colorSelections.length > 0) {
                memorySelections.forEach(memoryId => {
                    const memoryItem = this.spec[0].spec_items.find(item => item.id === memoryId);
                    colorSelections.forEach(colorId => {
                        const colorItem = this.spec[1].spec_items.find(item => item.id === colorId);
                        if (memoryItem && colorItem) {
                            this.selectedCombinations.push(`${memoryItem.item},${memoryId},${colorItem.item},${colorId}`);
                        }
                    });
                });
            } else if (memorySelections.length > 0) {
                // 只选择了内存，输出内存的 ID 和名称
                this.selectedCombinations = memorySelections.map(id => {
                    const memoryItem = this.spec[0].spec_items.find(item => item.id === id);
                    return memoryItem ? `${memoryItem.item},${id}` : '';
                }).filter(Boolean); // 过滤掉空值
            } else if (colorSelections.length > 0) {
                // 只选择了颜色，输出颜色的 ID 和名称
                this.selectedCombinations = colorSelections.map(id => {
                    const colorItem = this.spec[1].spec_items.find(item => item.id === id);
                    return colorItem ? `${colorItem.item},${id}` : '';
                }).filter(Boolean); // 过滤掉空值
            }

            this.setsSkuList = this.selectedCombinations.map(item => {
                // 拆分字符串
                let parts = item.split(','); // 根据 , 拆分

                // 获取内存名称、内存 ID、颜色名称和颜色 ID
                let name = parts[0]; // 内存名称
                let id = parseInt(parts[1]); // 内存 ID
                let colorname = parts[2]; // 颜色名称
                let colorid = parseInt(parts[3]); // 颜色 ID

                // 构建对象
                return {
                    id: id,
                    name: name,
                    colorname: colorname || '',
                    colorid: colorid || ''
                };
            });

        },
        openEditSku(indexs) {
            this.selectedSkuIndex = indexs;
            this.price = this.setsSkuList[indexs].price || ''; // 提前填充已有的价格
            this.stock = this.setsSkuList[indexs].stock || ''; // 提前填充已有的库存
            this.goodImg = this.setsSkuList[indexs].img==undefined?[]:[{url:this.setsSkuList[indexs].img}] || []; // 提前填充图片
            this.editSkuShow = true; // 打开弹窗
        },
        updateSku() {
            if (this.selectedSkuIndex !== null) {
                this.setsSkuList[this.selectedSkuIndex].price = this.price; // 更新价格
                this.setsSkuList[this.selectedSkuIndex].stock = this.stock; // 更新库存
                this.setsSkuList[this.selectedSkuIndex].img = this.goodImg.length<=0?'':this.goodImg[0].url; // 更新图片

            }
            this.editSkuShow = false; // 关闭弹窗
        },
        addSku() {
            this.$router.push({ path: '/addOrEditSku' })
        },
                // 上传封面正面
                async afterGoodReadFront(file) {
            try {
                this.ossParams = await getOssParams(this.$http);
                // 调用封装的上传函数
                await uploadImage(file, this.ossParams, this.goodImg);

                this.goodImg = this.goodImg.filter(item => {
                    return item.url
                })

            } catch (error) {
                console.error('处理上传错误:', error);
            }
        },
        // 删除
        uploadGoodDleteFront(file) {
            this.goodImg = uploadDelete(file, this.goodImg);
        },
        onSubmit() {
            let b = this.setsSkuList.map(item => ({
                sku_id: [item.id, item.colorid], // 组合 id 和 colorid
                sku_key: `${item.id}_${item.colorid}`, // 生成 sku_kry 字符串
                price: item.price, // 价格
                stock: item.stock // 库存
            }));
            console.log(b);

        }
    }
}
</script>
<style lang="scss">
.goods_sku {
    padding-top: 46px;

    .van-nav-bar .van-icon {
        color: #333333;
    }

    .van-nav-bar__arrow {
        font-size: 20px;
    }

    .van-hairline--bottom::after {
        display: none;
    }

    .goods_btn {
        // width: 95%;
        margin-right: .2rem;
        margin-top: .1rem;
        float: right;
    }

    .btn_sure {
        float: right;
        margin-right: .2rem;

    }

    .sku_list {
        width: 95%;
        margin: 0 auto;

        .sku_item {
            height: 1.24rem;
            background: #F2F4F5;
            border-radius: 6px;
            display: flex;
            justify-content: space-between;
            padding: .2rem;
            margin-bottom: .2rem;

            .sku_name {
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: .28rem;
                color: #333333;
                line-height: 1.24rem;
                text-align: left;
                font-style: normal;
            }

            .sku_price {
                width: 70%;
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: .28rem;
                color: #F32A23;
                line-height: .34rem;
                text-align: right;
                font-style: normal;
                margin-top: .2rem;

                div:last-child {
                    font-weight: 400;
                    font-size: .24rem;
                    color: #999999;
                    line-height: .34rem;
                    text-align: right;
                    font-style: normal;
                    margin-top: .12rem;
                }
            }

            .sku_icon {
                width: .32rem;
                line-height: 1.24rem;
                color: #999;
            }
        }
    }
}

.popup_title {
    text-align: center;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 16px;
    color: #333333;
    line-height: 22px;
    font-style: normal;
    padding: 0.2rem 0;
}

.good-box {
    width: 30%;
    margin: 0 auto;
}

.popup_btn_list {
    width: 90%;
    margin: 0 auto;
    padding-bottom: .4rem;
    display: flex;
    justify-content: space-between;

    .popup_btn {
        width: 45%;
    }

}
</style>